import React, {useEffect, useState} from 'react'
import {Form, Button, Input, Modal, Row, Col, Card, Select, notification} from 'antd'
import { connect } from 'umi'
import { getItemBySecurityId  } from '../../service'
import { getCompanyListAuth  } from '../../../service'
import EditSecurityPlanTable from "@/pages/Security/CommonAccumulationPlan/List/components/EditSecurityPlanTable";

const FormItem = Form.Item;
const {Option} = Select;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

const CreateForm = (props) => {

  const { onSubmit, onCancel, visible, type, current } = props;
  const [form] = Form.useForm();
  const [securityPlanItems,setSecurityPlanItems] = useState([]);
  const [contractData,setContractData] = useState([]);

  useEffect(() => {
    if (visible){
      getCompanyListAuth().then(res => {
        if(res.flag){
          res && setContractData(res.data)
        }else{
          notification.error({
            message: `请求错误 ${res.status}`,
            description: res.error,
          });
        }
      });
      if (current){
        getItemBySecurityId(current.securityId).then(res =>{
          current.securityItem = res;
          if (res.length>0){
            setSecurityPlanItems(res.map((item,index) =>{
              return {key: index, ...item}
            }));
          }
          form.setFieldsValue(current);
        })
      }
    }
  }, [visible]);

  const onChange = (values) => {
    setSecurityPlanItems(values);
  };

  const onFormCancel = () => {
    form.resetFields();
    setSecurityPlanItems([]);
    onCancel()
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    let { securityItem, ...formData } = fieldsValue;
    let securityName = formData.cityName + formData.unitName;
    onSubmit({...formData, securityItem: securityPlanItems, securityName: securityName});
    form.resetFields();
    setSecurityPlanItems([]);
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col span={0}>
            <FormItem name="securityId" label="方案ID">
              <Input type={"text"} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="cityName" label="参保地">
              <Input type={"text"} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitName" label="参保单位">
              <Select placeholder="请选择参保单位" showSearch filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} allowClear>
                { contractData.length>0 ? contractData.map((item, index) => {
                  return (
                    <Option value={item.name} key={index} lable={item}>
                      {item.name}
                    </Option>
                  )
                }) : ''}
              </Select>
            </FormItem>
          </Col>
          <Card title="添加公积金方案子项" bordered={false} className='widthStyle' style={{marginBottom:24}}>
          <FormItem name="securityItem">
            <EditSecurityPlanTable initData={securityPlanItems} onChange={onChange}/>
          </FormItem>
          </Card>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleSubmit()}>确认</Button>
      </>
    )
  }

  return (
    <Modal
      width={'90%'}
      destroyOnClose
      title="方案配置"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}


export default connect(({ user, personnel,global }) => ({
  global
}))(CreateForm)
